package org.example.demo.apiv2.sql;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.SelectItem;
import org.example.demo.apiv2.constant.CommonConstant;
import org.example.demo.apiv2.entity.FieldEntity;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FieldParser {

    /**
     * 构造jsqlparser的Column对象
     *
     * @param fieldEntity
     * @return
     */
    public static Column getColumn(FieldEntity fieldEntity) {
        return getColumn(fieldEntity.getTable(), fieldEntity.getTableAlias(), fieldEntity.getColName());
    }

    /**
     * 构造jsqlparser的Column对象
     *
     * @param tableName
     * @param tableAlias
     * @param colName
     * @return
     */
    public static Column getColumn(String tableName, String tableAlias, String colName) {
        Table table = TableParser.getTable(tableName, tableAlias, CommonConstant.useAs);
        return new Column(table, colName);
    }

    /**
     * 构造jsqlparser的SelectItem对象
     *
     * @param fieldEntity
     * @return
     */
    public static SelectItem<?> getSelectItem(FieldEntity fieldEntity) {
        Column column = FieldParser.getColumn(fieldEntity);
        return new SelectItem<>(column);
    }


    /**
     * 构造jsqlparser的SelectItem对象集合
     *
     * @param fieldEntityList
     * @return
     */
    public static List<SelectItem<?>> getSelectItemList(List<FieldEntity> fieldEntityList) {
        if (CollectionUtil.isEmpty(fieldEntityList)) {
            return new ArrayList<>();
        }
        List<SelectItem<?>> selectItemList = new ArrayList<>();
        for (FieldEntity fieldEntity : fieldEntityList) {
            SelectItem<?> selectItem = getSelectItem(fieldEntity);
            selectItemList.add(selectItem);
        }
        return selectItemList;
    }

}
